package com.appbee.core.server.requestfactory;

import javax.inject.Inject;

import com.appbee.core.server.model.HasLiveState;
import com.google.web.bindery.requestfactory.server.ServiceLayerDecorator;
import com.google.web.bindery.requestfactory.shared.Locator;
import com.google.web.bindery.requestfactory.shared.RequestContext;
import com.google.web.bindery.requestfactory.shared.ServiceLocator;
import com.google.inject.Injector;

public class AppServiceLayerDecorator extends ServiceLayerDecorator
{
	private final Injector injector;

	@Inject
	public AppServiceLayerDecorator(Injector injcetor)
	{
		this.injector = injcetor;
	}

	@Override
	public <T extends Locator<?, ?>> T createLocator(Class<T> clazz)
	{
		return injector.getInstance(clazz);
	}

	@Override
	public Object createServiceInstance(Class<? extends RequestContext> requestContext)
	{
		Class<? extends ServiceLocator> locatorType = getTop()
				.resolveServiceLocator(requestContext);
		ServiceLocator locator = injector.getInstance(locatorType);
		Class<?> serviceClass = getTop().resolveServiceClass(requestContext);
		return locator.getInstance(serviceClass);
	}

	// @Override
	// public Object createServiceInstance(Method contextMethod,
	// Method domainMethod)
	// {
	// Class<? extends ServiceLocator> locatorType = getTop()
	// .resolveServiceLocator(contextMethod, domainMethod);
	// ServiceLocator locator = injector.getInstance(locatorType);
	// return locator.getInstance(domainMethod.getDeclaringClass());
	// }

	@Override
	public boolean isLive(Object domainObject)
	{
		if(domainObject instanceof HasLiveState)
		{
			return ((HasLiveState)domainObject).isLive();
		}
		return super.isLive(domainObject);
	}

}
